
from typing import List


class BlockSorter:
    """按块的行数排序文本块，每个块由空行分隔"""

    def __init__(self, text: str, reverse: bool = False):
        """
        初始化类实例
        Args:
            text: 需要处理的原始文本（字符串）
            reverse: 是否倒序排序（默认 False 为升序）
        """
        self.text = text
        self.reverse = reverse


    def split_into_blocks(self) -> List[List[str]]:
        """将文本按空行分块"""
        blocks = []
        current_block = []

        for line in self.text.splitlines():
            if line.strip() == "":
                if current_block:
                    blocks.append(current_block)
                    current_block = []
            else:
                current_block.append(line)
        if current_block:
            blocks.append(current_block)

        return blocks

    def sort_blocks(self, blocks: List[List[str]]) -> List[List[str]]:
        """按每块的行数排序（可升序或倒序）"""
        return sorted(blocks, key=lambda b: len(b), reverse=self.reverse)

    @staticmethod
    def assemble_blocks(blocks: List[List[str]]) -> str:
        """将块重新组合成文本"""
        return "\n\n".join("\n".join(block) for block in blocks)

    def process_and_copy(self) -> str:
        """执行排序流程并返回结果字符串"""
        blocks = self.split_into_blocks()
        sorted_blocks = self.sort_blocks(blocks)
        result = self.assemble_blocks(sorted_blocks)
        return result


# 示例使用
if __name__ == "__main__":
    input_text = """苹果
香蕉

猫
狗
老虎

一
二
三
四
"""

    print("---- 升序 ----")
    sorter_asc = BlockSorter(input_text, reverse=False)
    print(sorter_asc.process_and_copy())

    print("\n---- 倒序 ----")
    sorter_desc = BlockSorter(input_text, reverse=True)
    print(sorter_desc.process_and_copy())
